import { controller, action, routeData, ContentResult, Controller } from "maishu-node-mvc";
import { weixinDataContext } from "../common";
import { WeiXinDataContext } from "../data-context";
import { DataHelper, SelectArguments } from "common";
import { createWeiXinSDK } from "../common";
import { guid } from "maishu-chitu-service";
import { LoginResult, statusCodes } from "maishu-node-auth/gateway";
import { currentAppId } from "common";
import { errors } from "../errors";

@controller("user")
export class UserController extends Controller {
    @action()
    async list(@weixinDataContext dc: WeiXinDataContext, @routeData { args }: { args: SelectArguments }) {
        let items = await DataHelper.list(dc.user, { selectArguments: args });
        return items;
    }

    @action()
    async login(@routeData { code }: { code: string }, @weixinDataContext dc: WeiXinDataContext, @currentAppId appId) {
        if (!appId) throw errors.cannotGetApplicationId();
        if (!code) throw errors.routeDataFieldNull("code");

        let wxSetting = await dc.settings.findOne({ id: appId });
        if (!wxSetting)
            throw errors.wxSettingNull();

        if (!wxSetting.AppId)
            throw errors.objectFieldNull("AppId", "wxSetting");

        let wx = createWeiXinSDK({
            appId: wxSetting.AppId, appKey: wxSetting.AppSecret,
            partnerId: wxSetting.PartnerId, partnerKey: wxSetting.PartnerKey,
            miniAppId: wxSetting.MiniProgramAppId, miniAppKey: wxSetting.MiniProgramSecret,
        })

        let r = await wx.access_token(code);
        let user = await dc.user.findOne({ openId: r.openid, applicationId: appId });
        if (user == null) {
            user = {
                id: guid(), openId: r.openid,
                createDateTime: new Date(Date.now()), applicationId: appId,
            }
            await dc.user.insert(user);
        }

        let loginResult: LoginResult = { userId: user.id };
        return new ContentResult(JSON.stringify(loginResult), "application/json", statusCodes.login);
    }
}